package com.qf.application.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qf.application.entity.User;
import com.qf.application.mapper.UserMapper;
import com.qf.application.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.application.utils.exception.AppException;
import org.mindrot.jbcrypt.BCrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author l
 * @since 2024-07-04
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public User getUserByNameAndPassword(String name,String password) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", name);
        User user = this.baseMapper.selectOne(queryWrapper);
        if(user == null){
            throw new AppException(301,"用户名不存在");
        }

        if (!BCrypt.checkpw(password,user.getPassword())) {
            throw new AppException(302,"用户名或密码错误");
        }
        return user;
    }

    @Override
    public Boolean getUserByName(String username) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        User user = this.baseMapper.selectOne(queryWrapper);
        if(user != null){
            throw new AppException(303,"用户名已存在");
        }
        return true;
    }

    @Override
    public Boolean saveUserInfo(User user) {
        return this.baseMapper.addUserInfo(user);
    }
}
